package com.qhgrain.api.comm.datadictionary.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.StringUtil;
import com.pubframework.common.util.datetime.DateUtil;
import com.qhgrain.api.comm.datadictionary.dao.DataDictionaryMapper;
import com.qhgrain.api.comm.datadictionary.entity.DataDictionary;
import com.qhgrain.api.comm.datadictionary.service.IDataDictionaryService;
import com.qhgrain.gway.util.UUIDUtil;

@Transactional(rollbackFor = Exception.class)
@Service("dataDictionaryService")
public class DataDictionaryServiceImpl implements IDataDictionaryService {

	@Autowired
	public DataDictionaryMapper dataDictionaryMapper;

	@Transactional(readOnly = false)
	@Override
	public void insertDic(DataDictionary dataDictionary) {
		dataDictionary.setDcCreateTime(DateUtil.now());
		dataDictionary.setDcLastUpdateTime(DateUtil.now());
		if (null == dataDictionary.getDcSysCode()) {
			dataDictionary.setDcSysCode("");
		}
		if (null == dataDictionary.getDcSysName()) {
			dataDictionary.setDcSysName(dataDictionary.getDcSysCode());
		}
		if (null == dataDictionary.getDcCreateUserName()) {
			dataDictionary
					.setDcCreateUserName(dataDictionary.getDcCreateUser());
		}
		dataDictionary.setDcCode(getNextCode(dataDictionary.getDcPcode()));
		dataDictionary.setDcId(UUIDUtil.getUUID());
		dataDictionaryMapper.insert(dataDictionary);
	}

	@Override
	public Page<DataDictionary> queryListForPage(int pageNo, int pageSize,
			Map<String, String> conditionMap) {
		Example example = new Example(DataDictionary.class);
		if (null != conditionMap) {
			Criteria c = example.createCriteria();
			if (conditionMap.containsKey("dcCode")) {
				String dcCode = conditionMap.get("dcCode");
				c.andEqualTo("dcCode", dcCode);
			}
			if (conditionMap.containsKey("dcPcode")) {
				String dcPcode = conditionMap.get("dcPcode");
				c.andEqualTo("dcPcode", dcPcode);
			}
			if (conditionMap.containsKey("dcName")) {
				String dcName = conditionMap.get("dcName");
				c.andLike("dcName", "%" + dcName + "%");
			}
			if (conditionMap.containsKey("dcSysCode")) {
				String dcSysCode = conditionMap.get("dcSysCode");
				c.andLike("dcSysCode", "%" + dcSysCode + "%");
			}
			if (conditionMap.containsKey("dcSysName")) {
				String dcSysName = conditionMap.get("dcSysName");
				c.andLike("dcSysName", "%" + dcSysName + "%");
			}
			if (conditionMap.containsKey("dcIsDeleted")) {
				String dcIsDeleted = conditionMap.get("dcIsDeleted");
				c.andEqualTo("dcIsDeleted", dcIsDeleted);
			}
		}
		Page<DataDictionary> page = PageHelper.startPage(pageNo, pageSize);
		dataDictionaryMapper.selectByExample(example);
		// 查询总数
		return page;
	}

	/**
	 * 根据父字典编码得到下一个子字典的编码 2016年4月14日 下午5:49:23
	 * 
	 * @tags 1_1_2
	 * @author zhaoyq
	 */
	public synchronized String getNextCode(String pCode) {
		pCode = StringUtils.defaultIfBlank(pCode, "");
		String result = "";
		Map<String, String> conditionMap = new HashMap<String, String>();
		if(StringUtil.isNotEmpty(pCode)&&!"null".equals(pCode)){
			conditionMap.put("dcPcode", pCode);
		}
		//查询子字典
		List<DataDictionary> dataDictionaries = queryListForPage(1, Integer.MAX_VALUE, conditionMap);
		Integer intCode;
		//子字典为空
		if(null == dataDictionaries || dataDictionaries.isEmpty()){
			if(pCode.equals("")){
				result = "1";
			}else{
				result = pCode+"_1";
			}
		}else{
			intCode = getMaxCode(dataDictionaries);
			result = pCode + "_" + (intCode+1);
		}
	
		return result;
	}
	/**
	 * 
	 * 2016年5月9日 下午4:35:43  
	 * @tags 获取子字典中最大的编码的尾数
	 * @param 子字典列表
	 * @author zhaoyq
	 */
	public int getMaxCode(List<DataDictionary> dataDictionaries){
		int code = 1;
		int lastCode;
		for(DataDictionary dic : dataDictionaries){
			String dicCode = dic.getDcCode();
			if(StringUtils.isNotBlank(dicCode)){
				try {
					lastCode = new Integer( dicCode.substring(dicCode.lastIndexOf("_") + 1));
				} catch (Exception e) {
					lastCode = 1;
				}
				
				code = code >= lastCode ? code : lastCode;
			}
		}
		return code;
	}
	@Override
	public DataDictionary getDataDicById(String dicId) {
		return dataDictionaryMapper.selectByPrimaryKey(dicId);
	}

	@Transactional(readOnly = false)
	@Override
	public void deleteById(String dicId) {
		dataDictionaryMapper.deleteByPrimaryKey(dicId);
	}

	@Transactional(readOnly = false)
	@Override
	public void update(DataDictionary dataDictionary) {

		Example example = new Example(DataDictionary.class);
		Criteria c = example.createCriteria();
		c.andEqualTo("dcId", dataDictionary.getDcId());
		dataDictionary.setDcLastUpdateTime(DateUtil.now());
		// 如果字典名称不为空，则修改整个实体（需额外判断父节点是否变更）否则只是修改状态
		if (StringUtils.isNotBlank(dataDictionary.getDcName())) {
			DataDictionary pdataDictionary = getDataDicById(dataDictionary
					.getDcId());
			String oldPCode = StringUtils.defaultIfBlank(
					pdataDictionary.getDcPcode(), "");
			String newPCode = StringUtils.defaultIfBlank(
					dataDictionary.getDcPcode(), "");
			if (!newPCode.equals(oldPCode)) {
				// 如果修改了所属父字典 重新生成编码
				dataDictionary.setDcCode(getNextCode(newPCode));
				// 同时修改父字典编码
				dataDictionary.setDcPcode(newPCode);
			}
		}

		dataDictionaryMapper.updateByExampleSelective(dataDictionary, example);
	}

	/**
	 * 根据系统编码和父节点得到所有下级字典
	 */
	@Override
	public List<DataDictionary> getChildDataDic(String sysCode, String dicPcode) {
		Example example = new Example(DataDictionary.class);
		Criteria c = example.createCriteria();
		if(StringUtil.isNotEmpty(sysCode) && !"null".equals(sysCode)){
			c.andEqualTo("dcSysCode", sysCode);
		}
		if(StringUtil.isNotEmpty(dicPcode) && !"null".equals(dicPcode)){
			c.andLike("dcPcode", dicPcode + "%");
		}
		//默认查启用的
		c.andEqualTo("dcIsDeleted",  "0");
		List<DataDictionary> dataDictionaries = dataDictionaryMapper
				.selectByExample(example);
		return dataDictionaries;
	}

	@Override
	public DataDictionary getDataDicInfoByCode(String dcCode) {
		DataDictionary record = new DataDictionary();
		record.setDcCode(dcCode);
		return dataDictionaryMapper.selectOne(record);
	}

	@Override
	public List<Map<String, String>> getSystemList() {
		List<Map<String, String>> syList = dataDictionaryMapper.getSystemList();
		return syList;
	}
	@Override
	public void updateStaus(List<String> ids, String status) {
		if(ids == null || ids.size() == 0) return;
		this.dataDictionaryMapper.updateStatus(ids, status);
		
	}
}
